<?php


namespace seecms\lib;

use seecms\See;
use seecms\SeeLang;
use magein\utils\Result;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

class Mailer
{
    /**
     * @var array|string
     */
    protected $config = '';

    /**
     * @var PHPMailer
     */
    protected $mail = null;

    public function __construct($config = null)
    {
        if (empty($config)) {
            $config = See::provider()->general->smtp ?: [];
        }

        $mail = new PHPMailer(true);
        $mail->SMTPDebug = SMTP::DEBUG_OFF;
        $mail->isSMTP();
        $mail->Host = $config['domain'] ?? '';
        $mail->SMTPAuth = true;
        $mail->Username = $config['send_email'] ?? '';
        $mail->Password = $config['send_password'] ?? '';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $config['port'] ?? '';
        $mail->CharSet = PHPMailer::CHARSET_UTF8;
        $this->mail = $mail;

        $this->config = $config;
    }

    /**
     * @param array|string $receive
     * @param string $subject
     * @param string $body
     * @param string|null $alt_body
     * @return Result
     */
    public function html($receive, string $subject, string $body, string $alt_body = null): Result
    {
        if (empty($body)) {
            return Result::error('The email content is empty');
        }

        if (empty($this->mail)) {
            return Result::error('The smtp service has not been configured yet');
        }

        try {
            $this->mail->setFrom($this->config['send_email'], $this->config['send_name'], false);
            if (is_array($receive)) {
                foreach ($receive as $item) {
                    $this->mail->addAddress($item);
                }
            } else {
                $this->mail->addAddress($receive);
            }
            $this->mail->addReplyTo($this->config['send_email']);
            $this->mail->Subject = $subject;
            $this->mail->Body = $body;
            $this->mail->AltBody = $alt_body ?: $body;
            $this->mail->send();
        } catch (\Exception $exception) {
            return Result::error($exception->getMessage());
        }

        return Result::success(true, SeeLang::operate('email_success'));
    }

    /**
     * @param array|string $receive
     * @param string $subject
     * @param string $text
     * @return Result
     */
    public function text($receive, string $subject, string $text): Result
    {
        if ($this->mail) {
            $this->mail->isHTML(false);
        }
        return $this->html($receive, $subject, $text);
    }

    /**
     * 添加附件
     * @param $filepath
     * @return void
     * @throws Exception
     */
    public function addAttachment($filepath)
    {
        $this->mail->addAttachment($filepath);
    }
}